﻿namespace WPCloudAppIteration2.Phone.Pages
{
    using System;
    using System.Device.Location;
    using System.Windows;
    using System.Windows.Navigation;
    using Microsoft.Phone.Controls;
    using Microsoft.Phone.Shell;
    using Microsoft.Phone.Tasks;
    using WPCloudAppIteration2.Phone.Helpers;
    using WPCloudAppIteration2.Phone.ViewModel;

    public partial class UploadPhotoPage : PhoneApplicationPage
    {
        private GeoCoordinateWatcher watcher;
        private string latitude;
        private string longitude;

        public UploadPhotoPage()
        {
            this.InitializeComponent();

            this.ViewModel = new UploadPhotoPageViewModel();
        }

        public UploadPhotoPageViewModel ViewModel
        {
            get { return this.DataContext as UploadPhotoPageViewModel; }
            set { this.DataContext = value; }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var photoResult = PhoneHelpers.GetApplicationState<PhotoResult>("PhotoResult");

            if (this.watcher == null)
            {
                // Use high accuracy.
                this.watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);

                this.watcher.MovementThreshold = 20;

                // Use MovementThreshold to ignore noise in the signal.
                this.watcher.StatusChanged += this.GeoCoordinateWatcherStatusChanged;
            }

            this.watcher.Start();

            if ((this.ViewModel != null) && (photoResult != null))
            {
                this.ViewModel.LoadPhoto(photoResult);
            }
            else
            {
                this.NavigationService.GoBack();
            }
        }

        private void ContainerName_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            this.ViewModel.ContainerName = (string)ContainerName.SelectedItem;
        }

        private void GeoCoordinateWatcherStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            if (e.Status == GeoPositionStatus.Ready)
            {
                var co = this.watcher.Position.Location;
                this.latitude = co.Latitude.ToString("0.000");
                this.longitude = co.Longitude.ToString("0.000");

                this.watcher.Stop();
            }
        }

        private void OnUploadPicture(object sender, RoutedEventArgs e)
        {
            if (this.ViewModel != null)
            {
                if (string.IsNullOrWhiteSpace(this.ViewModel.BlobName))
                {
                    MessageBox.Show("The blob name cannot be null nor empty.", "Upload Photo Result", MessageBoxButton.OK);
                }
                else if (string.IsNullOrWhiteSpace(this.ViewModel.ContainerName))
                {
                    MessageBox.Show("The container name cannot be null nor empty.", "Upload Photo Result", MessageBoxButton.OK);
                }
                else
                {
                    var userIdentifier = App.CloudClientFactory.UserName;

                    try
                    {
                        this.ViewModel.UploadPhoto(
                            this.latitude,
                            this.longitude,
                            userIdentifier,
                            successMessage =>
                            {
                                this.Dispatcher.BeginInvoke(
                                    () =>
                                    {
                                        MessageBox.Show("Upload successful", "Upload Photo Result", MessageBoxButton.OK);
                                        PhoneHelpers.RemoveApplicationState("PhotoResult");
                                        PhoneHelpers.SetApplicationState("LoadContainers", true);
                                        this.NavigationService.GoBack();
                                    });
                            },
                            errorMessage =>
                            {
                                this.Dispatcher.BeginInvoke(
                                    () =>
                                    {
                                        MessageBox.Show(errorMessage, "Upload Photo Result", MessageBoxButton.OK);
                                        PhoneHelpers.SetApplicationState("LoadContainers", true);
                                    });
                            });
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(exception.Message, "Upload Photo Result", MessageBoxButton.OK);
                        this.NavigationService.GoBack();
                    }
                }
            }
        }
    }
}